<template>
	<view>
		<scroll-view style="height: 100%;" scroll-y="true">
			<view v-if="selectedImages.length > 0">
				<view class="image-grid">
					<view v-for="(imagePath, index) in selectedImages" :key="index">
						<uni-card :is-full="true" spacing="0px" padding="0px">
							<image :src="imagePath.url" class="imgitem"
								:class="{'enlarged-image': previewImages[index]}" mode="aspectFill"
								@click="toggleImagePreview(index)" />
							<uni-icons class="tip" :color="getColor(index)" size="18" :type="getIcon(index)"
								@click="removeImage(index)" />
							<uni-data-checkbox v-model="imagePath.checkbox" :localdata="range"
								class="dataCheckbox"></uni-data-checkbox>
							<uni-easyinput type="text" :autoHeight="true" class="uni-mt-3" trim="all"
								v-model="imagePath.input" placeholder="照片备注"></uni-easyinput>
						</uni-card>
					</view>
				</view>
			</view>
			<view v-else>
				<view class="empty-content" style="margin: 0 20rpx;">
					<pinapp-empty-page></pinapp-empty-page>
				</view>
			</view>
		</scroll-view>
		<!-- <progress v-if="uploading" :percent="uploadPercent" /> -->
		<view class="btngroups">
			<!-- <button v-if="selectedImages.length > 0" @click="uploadImages" :disabled="uploading" style="">
				<uni-icons size="80" type="cloud-upload-filled" color="#007aff" @click="openMedia" /></button> -->
			<vfabVue :fabStyle="fabStyle" :vmenu="vmenu" @vtrigger="trigger"></vfabVue>
		</view>



	</view>
</template>

<script setup>
	import {
		computed,
		onMounted,
		ref,
		getCurrentInstance
	} from 'vue';
	import prefix from '@/utils/prefix.js';
	import vfabVue from "@/components/vfab/vfab.vue";

	import {
		onLoad
	} from '@dcloudio/uni-app';

	const imgvalue = ref([]);
	const selectedImages = ref([]);
	const uploading = ref(false);
	const uploadPercent = ref(0);
	const previewImages = ref([]);
	const isUploaded = ref(new Array(selectedImages.value.length).fill(false));
	const horizontal = ref("left");
	const stock = ref(null);
	var typeList = ref([]);
	const range = ref([{
		"value": 0,
		"text": "拍摄前"
	}, {
		"value": 1,
		"text": "拍摄后"
	}])
	const fabStyle = ref({
		horizontal: 'right',
		vertical: 'bottom',
		direction: 'horizontal', //vertical
	})
	const vmenu = ref([{
			iconPath: '/static/img/pz_active.png',
			selectedIconPath: '/static/img/pz_active.png',
			text: '选择照片',
			active: false
		},
		{
			iconPath: '/static/img/fenlei_active.png',
			selectedIconPath: '/static/img/fenlei_active.png',
			text: '上传照片',
			active: false
		}
	])
	const $instance = ref(getCurrentInstance().proxy)

	//获取物流集装箱信息
	onLoad((options) => {
		const eventChannel = $instance.value.getOpenerEventChannel();
		eventChannel.once('stock', (value) => {

			stock.value = value.data;
		})

	})

	//悬浮框选择照片按钮触发
	const openMedia = () => {
		uni.chooseImage({
			count: 6,
			sourceType: ['camera', 'album'],
			success: (res) => {
				for (let item in res.tempFilePaths) {
					var imgs = {
						url: res.tempFilePaths[item],
						checkbox: 0,
						input: ""
					};
					selectedImages.value.push(imgs);
				}
				imgvalue.value = res.tempFilePaths;

				previewImages.value = new Array(res.tempFilePaths.length).fill(false);
				isUploaded.value = new Array(res.tempFilePaths.length).fill(false);
				// 添加过渡动画类名
				// document.getElementsByClassName('.image-grid view').forEach((item, index) => {
				// 	item.classList.add('fade-in');
				// 	setTimeout(() => {
				// 		item.classList.remove('fade-in');
				// 	}, 500);
				// });


			},
		});
	};
	//照片上传
	const uploadImages = (e) => {

		uploading.value = true;
		try {
			var token = uni.getStorageSync("Authorization");
		} catch (e) {

		}

		const imageUploadPromises = selectedImages.value.map((filePath, index) => {
			return new Promise((resolve, reject) => {

				if (filePath.input == "" || filePath.checkbox == null) {
					uni.showModal({
						title: '提示',
						content: '照片备注或拍摄时不能为空',
						showCancel: false,
					});
				} else {
					uni.compressImage({
						src: filePath.url,
						quality: 70,
						success: res => {
							uni.uploadFile({
								url: prefix + 'Picture/UploadImage',
								filePath: res.tempFilePath,
								name: 'file',
								header: {
									Authorization: token,
								},
								formData: {
									userName: uni.getStorageSync("userName"),
									fchrExportStockNo: stock.value
										.fchrExportStockNo,
									ftinorder: stock.value.ftinorder,
									position: filePath.input,
									isBeforeOrAfter: filePath.checkbox
								},
								success: (res) => {
									if (res.statusCode === 200) {
										isUploaded.value[index] = true;
										resolve(res);
									} else {
										isUploaded.value[index] = false;
										reject(res);
									}
								},
								fail: (err) => {
									uni.showModal({
										title: '提示',
										content: '上传失败',
										showCancel: false,
									});
									isUploaded.value[index] = false;
									reject(err);
								},
								onProgressUpdate: (res) => {
									if (index === selectedImages.value.length -
										1) {
										uploadPercent.value = res.progress;
									}
								},
							});
						}
					})


				}

			});
		});
		Promise.all(imageUploadPromises)
			.then((res) => {

				if (res.length > 0) {
					uni.showToast({
						title: '上传完成',
						icon: 'success',
					});
					setTimeout(() => {
						selectedImages.value = [];
					}, 1000)
				} else {
					uni.showToast({
						title: '上传失败',
						icon: 'error',
					});
					setTimeout(() => {
						selectedImages.value = [];
					}, 1000)
				}
			})
			.catch((e) => {
				console.log(e)
				uni.showToast({
					title: '部分上传失败',
					icon: 'error',
				});
			})
			.finally(() => {
				uploading.value = false;
			});


	};


	//照片预览
	const toggleImagePreview = (index) => {
		previewImages[index] = !previewImages[index];
		if (previewImages[index]) {
			uni.previewImage({
				urls: imgvalue.value,
				current: index,
			});
		}
	};

	const removeImage = (index) => {
		selectedImages.value.splice(index, 1);
		imgvalue.value.splice(index, 1);
		previewImages.value.splice(index, 1);
		isUploaded.value.splice(index, 1);
	};

	const getIcon = (index) => {
		if (isUploaded.value[index]) {
			return 'checkmarkempty';
		} else {
			return 'closeempty';
		}
	};

	const getColor = (index) => {
		if (isUploaded.value[index]) {
			return '#00ff00';
		} else {
			return '#ff0000';
		}
	};


	const trigger = (e) => {
		if (e.index == 0) {
			openMedia();
		} else if (e.index == 1) {
			uploadImages();
		} else {
			//其他情况
		}
	}
</script>

<style>
	@import url('@/static/styles/home.css');
</style>